package source.events.action;

import source.model.type.ActionResult;
import source.model.DataHandler;
import source.model.utility.EatAtJoesIterator;
import source.model.ObjectID;
import source.view.MainScreen;
import source.model.Unit;
import source.model.type.GameObjectType;
/**
 * NextUnit class is responsible for selecting the next available unit with movement
 * left.  If no units have movement left, a warning is displayed.
 * @author Joe
 *
 */
public class NextUnit implements Action{

	private int playerID;
	
	public NextUnit(int playerID)
	{
		this.playerID = playerID;
	}
	public ActionResult execute(DataHandler dh)
	{

		EatAtJoesIterator units = dh.getUnitIterator();
		if(units.getLength() == 0)
		{
			MainScreen.writeToConsole("Player owns no units to select");
			return ActionResult.FAILED;
		}
		if(dh.getCurrentSelection().objectType() == GameObjectType.UNIT && units.getLength() == 1)
		{
			MainScreen.writeToConsole("Player owns only one unit to select");
			return ActionResult.FAILED;
		}
		Unit u;
		ObjectID nextUnit;
		for( int i = 0; i < units.getLength(); i++)
		{
			nextUnit = units.getNext();
			if ( nextUnit == null ) {
				//MainScreen.writeToConsole("NextUnit:  EatAtJoesIterator.nextUnit is null");
				return ActionResult.IMPOSSIBLE;
			}
			u = (Unit)dh.objectQuery(nextUnit);
			if(!u.getMissionFlag())
			{
				dh.setCurrentSelection(nextUnit);
				MainScreen.writeToConsole(u.getType() + " successfully was selected");
				return ActionResult.SUCCESS;
			}
		}
		MainScreen.writeToConsole("All Units are on a mission.  Cannot select a unit");
		return ActionResult.FAILED;
	}
}
